﻿using System;
using System.Collections.Generic;
using System.Linq;
using Grishko.DataTier;
using Grishko.SerilizeTools;
using OutdoorLib.BaseEntity.Constraction;
using Ecopsy.Tools;
using System.Data;
using System.Xml;

namespace OutdoorLib.BaseEntity.Contract
{
    
    /// <summary>
    /// Элемент расписания поверхности  
    /// </summary>    
    public class SurfaceSheduleItem : EntitySingle
    {
        public string SideID { get; set; }
        public int SurfNumber { get; set; }
        public DateTime dtStart { get; set; }
        public DateTime dtFinish  { get; set; }
        public string ContractId { get; set; }
        public string ContractStatusTypeID { get; set; }

    }

    
    public class SideShedule : EntityList
    {       
        /// <summary>
        /// Запустить функцию Distribute  - считать загрузку
        /// </summary>
        /// <param name="SideID"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <returns></returns>
        public static SideShedule GetSideShedule (  string SideID,
                                                    DateTime dtStart, 
                                                    DateTime dtEnd)
        {
            SideShedule result = new SideShedule() { dtStart = dtStart, dtEnd = dtEnd };
            SecuretyContext SC = AppContext.GetSC();
            Side s = (Side)SqlTools.GetEntitySingle(SideID);            
            result.Side = s;            
            return result ;
            
        }

        public DateTime dtStart { get; set; }
        public DateTime dtEnd { get; set; }
        public Side Side { get; set; }
        public string SideID { get { return Side .ID; } }

        /// <summary>
        /// Признак наличия очереди 
        /// </summary>
        [EntityNonSerialized] 
        public bool IHave_Q 
        {
            get 
            {
                return MaxSurfValue > this.Side.SurfaceCount-1;
            }
        }
        /// <summary>
        /// Максмальное значение поверъхности в очереди
        /// </summary>
        public int MaxSurfValue 
        { 
            get 
            {
                List<SurfaceSheduleItem> l = this.ToList<SurfaceSheduleItem>();
                return (l.Count > 0 ? this.ToList<SurfaceSheduleItem>().Max(w => w.SurfNumber) : 0); 
                
            } 
        } 

        /// <summary>
        ///  Вернуть SurfaceSheduleItem Если есть пересечение по периоду и номеру поверхности 
        /// </summary>
        /// <param name="DtStart"></param>
        /// <param name="DtEnd"></param>
        /// <param name="SurfaceNumber"></param>
        /// <param name="CrossTrype">Тип пересечения отрезков</param>
        /// 
        /// <returns></returns>
        public SurfaceSheduleItem GetSurfaceSheduleItem(DateTime DtStart, 
                                                        DateTime DtEnd, 
                                                        int SurfaceNumber, 
                                                        ref int CrossTrype)
        {
            this.Reset();
            SurfaceSheduleItem res=null;
            foreach (SurfaceSheduleItem i in this)
            {
                if (i.SurfNumber == SurfaceNumber)
                {
                    CrossTrype = Ecopsy.Tools.DateTimeTools.GetCrossPeriod(DtStart, DtEnd, i.dtStart, i.dtFinish);
                    
                    if (CrossTrype == 1||CrossTrype ==4)
                        res = i;
                }       
            }
            return res ;

        }

        public override void Load()
        {
            string SqlLoadText_Format="select * from dbo.SideSurfaceDistribution ('{0}','{1}','{2}') FOR XML RAW, ROOT('Distribution')";
            string[] CmdParams = { SideID, DateTimeTools.GetSqlDate(dtStart), DateTimeTools.GetSqlDate(dtEnd) };
            object obj= SqlTools.ExecuteSqlText (string.Format (SqlLoadText_Format ,CmdParams ));
            
            if(null!=obj)
                LoadItems(obj.ToString());
        }

        /// <summary>
        /// Прогружает строки из XML
        /// </summary>
        /// <param name="XML"></param>
        public void LoadItems(string sXML)
        {
            XmlDocument d = new XmlDocument();
            d.LoadXml(sXML);
            foreach (XmlNode nd in d.FirstChild.ChildNodes)
            {
                SurfaceSheduleItem i = new SurfaceSheduleItem();
                i.ReadXml(nd);
                this.Add(i);
            }       
        }

        
    }
}
